package com.cmcc.groupcontacts.common;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.provider.CallLog;
import android.util.Log;

import com.cmcc.groupcontacts.util.ExceptionHandler;

/**
 * 核心服务
 * 
 * @author
 * 
 */
public class CoreService extends Service {
	private static final String LOG_TAG = "CoreService";
	
	/** 电话拨打状态Action */
	public static final String PHONE_STATE_ACTION = "android.intent.action.PHONE_STATE";
	/** 短信接收Action */
	public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	/** 彩信接收Action */
	public static final String WAP_PUSH_RECEIVED_ACTION = "android.provider.Telephony.WAP_PUSH_RECEIVED";
	/** 短信接收DataType */
	public static final String WAP_PUSH_RECEIVED_DATATYPE = "application/vnd.wap.mms-message";

	private CallLogObserver observer;
	
	/** 核心服务是否运行 */
	public static boolean isRunning = false;
	/** 系统通知ID计数器 */
	public static int notificationIdCounter = 1001;
	
	@Override
	public void onCreate() {
		Log.v(LOG_TAG, "核心服务启动");
		super.onCreate();

		isRunning = true;

		startCallReceiver();
		registerCallLogObserver();

		startSmsReceiver();
	}

	/*
	 * 启动来电监听接收器
	 */
	private void startCallReceiver() {
		try {
			Log.v(LOG_TAG, "启动来电监听接收器");
			IntentFilter filter = new IntentFilter(PHONE_STATE_ACTION);
			filter.setPriority(2147483647);
			CallReceiver callReceiver = new CallReceiver();
			registerReceiver(callReceiver, filter);
		} catch (Exception e) {
			ExceptionHandler.handle(e, "启动来电监听接收器时出错");
		}
	}

	/*
	 * 注册通话记录观察者
	 */
	private void registerCallLogObserver() {
		observer = new CallLogObserver(this);
		getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true, observer);
	}

	/*
	 * 启动信息监听接收器
	 */
	private void startSmsReceiver() {
		try {
			Log.v(LOG_TAG, "启动短信监听接收器");
			IntentFilter smsFilter = new IntentFilter(SMS_RECEIVED_ACTION);
			smsFilter.setPriority(2147483647);
			registerReceiver(new SmsReceiver(), smsFilter);

			Log.v(LOG_TAG, "启动彩信监听接收器");
			IntentFilter mmsFilter = new IntentFilter(WAP_PUSH_RECEIVED_ACTION, WAP_PUSH_RECEIVED_DATATYPE);
			mmsFilter.setPriority(2147483647);
			registerReceiver(new SmsReceiver(), mmsFilter);
		} catch (Exception e) {
			ExceptionHandler.handle(e, "启动信息监听接收器时出错");
		}
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		Log.v(LOG_TAG, "核心服务销毁");
		super.onDestroy();

		unregisterObserver();

		isRunning = false;
	}

	private void unregisterObserver() {
		getContentResolver().unregisterContentObserver(this.observer);
	}
}
